package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"strings"

	"github.com/golang/glog"
)

func rootHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("entering root handler")
	// 1.接收客户端 request，并将 request 中带的 header 写入 response header
	// header设置请放到前面
	for k, v := range r.Header {
		w.Header().Set(k, v[0])
	}
	// 2.读取当前系统的环境变量中的 VERSION 配置，并写入 response header
	env := os.Getenv("VERSION")
	w.Header().Set("VERSION", env)
	// 3.Server 端记录访问日志包括客户端 IP，HTTP 返回码，输出到 server 端的标准输出

	clientip := getCurrentIP(r)
	log.Printf("Success! Response code: %d", 200)
	log.Printf("Success! clientip: %s", clientip)
	user := r.URL.Query().Get("user")
	if user != "" {
		io.WriteString(w, fmt.Sprintf("hello [%s]\n", user))
	} else {
		io.WriteString(w, "hello [stranger]\n")
	}
	io.WriteString(w, "===================Details of the http request header:============\n")

	for k, v := range r.Header {
		io.WriteString(w, fmt.Sprintf("%s=%s\n", k, v))
	}

}

func healthz(w http.ResponseWriter, r *http.Request) {
	// 4.当访问 localhost/healthz 时，应返回200
	w.Write([]byte("hello healthz\n"))
	io.WriteString(w, "200\n")
	w.WriteHeader(200)
}

func getCurrentIP(r *http.Request) string {
	// 这里也可以通过X-Forwarded-For请求头的第一个值作为用户的ip
	// 但是要注意的是这两个请求头代表的ip都有可能是伪造的
	ip := r.Header.Get("X-Real-IP")
	if ip == "" {
		// 当请求头不存在即不存在代理时直接获取ip
		ip = strings.Split(r.RemoteAddr, ":")[0]
	}
	return ip
}
func ClientIP(r *http.Request) string {
	xForwardedFor := r.Header.Get("X-Forwarded-For")
	ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
	if ip != "" {
		return ip
	}
	ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
	if ip != "" {
		return ip
	}
	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
		return ip
	}
	return ""
}
func main() {
	os.Setenv("VERSION", "ROBOT")
	flag.Set("v", "4")
	glog.V(2).Info("Starting http server...")

	http.HandleFunc("/", rootHandler)
	http.HandleFunc("/healthz", healthz)

	c, python, java := true, false, "no!"
	fmt.Println(c, python, java)

	err := http.ListenAndServe(":80", nil)
	if err != nil {
		log.Fatal(err)
	}
}
